<template>
  <div class="reservoir-boundary-container">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" :inline="true" label-width="80px">
        <el-form-item label="边界名称">
          <el-input
            v-model="queryForm.boundaryName"
            placeholder="请输入边界名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="边界类型">
          <el-select
            v-model="queryForm.boundaryType"
            placeholder="请选择边界类型"
            clearable
            style="width: 150px"
          >
            <el-option label="主坝" value="main-dam" />
            <el-option label="副坝" value="sub-dam" />
            <el-option label="溢洪道" value="spillway" />
            <el-option label="输水隧洞" value="tunnel" />
            <el-option label="库区" value="reservoir-area" />
            <el-option label="管理区" value="management-area" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="正常" value="normal" />
            <el-option label="维护中" value="maintenance" />
            <el-option label="异常" value="abnormal" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增边界
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedIds.length === 0"
          @click="handleBatchDelete"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="warning" @click="handleViewMap">
          <el-icon><Location /></el-icon>
          查看地图
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="boundaryCode" label="边界编号" width="120" />
        <el-table-column prop="boundaryName" label="边界名称" min-width="150" />
        <el-table-column prop="boundaryType" label="边界类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.boundaryType)">
              {{ getTypeText(row.boundaryType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="coordinates" label="坐标信息" min-width="200" />
        <el-table-column prop="length" label="边界长度" width="100">
          <template #default="{ row }">
            {{ row.length }}m
          </template>
        </el-table-column>
        <el-table-column prop="area" label="覆盖面积" width="100">
          <template #default="{ row }">
            {{ row.area }}㎡
          </template>
        </el-table-column>
        <el-table-column prop="manager" label="管理员" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <ReservoirBoundaryFormDialog
      v-model:visible="formDialogVisible"
      :form-data="currentFormData"
      :is-view="isView"
      @success="handleFormSuccess"
    />

    <!-- 地图弹窗 -->
    <BoundaryMapDialog
      v-model:visible="mapDialogVisible"
      :boundary-data="tableData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Download, Location } from '@element-plus/icons-vue'
import ReservoirBoundaryFormDialog from './components/ReservoirBoundaryFormDialog.vue'
import BoundaryMapDialog from './components/BoundaryMapDialog.vue'

// 查询表单
const queryForm = reactive({
  boundaryName: '',
  boundaryType: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedIds = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗控制
const formDialogVisible = ref(false)
const mapDialogVisible = ref(false)
const currentFormData = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    'main-dam': 'danger',
    'sub-dam': 'warning',
    'spillway': 'primary',
    'tunnel': 'info',
    'reservoir-area': 'success',
    'management-area': ''
  }
  return typeMap[type] || ''
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    'main-dam': '主坝',
    'sub-dam': '副坝',
    'spillway': '溢洪道',
    'tunnel': '输水隧洞',
    'reservoir-area': '库区',
    'management-area': '管理区'
  }
  return typeMap[type] || type
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    normal: 'success',
    maintenance: 'warning',
    abnormal: 'danger'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    normal: '正常',
    maintenance: '维护中',
    abnormal: '异常'
  }
  return statusMap[status] || status
}

// 模拟API - 获取边界列表
const fetchBoundaryList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const mockData = [
      {
        id: 1,
        boundaryCode: 'BD001',
        boundaryName: '主坝东段边界',
        boundaryType: 'main-dam',
        coordinates: '116.123456,39.654321;116.234567,39.765432',
        length: 1250,
        area: 15600,
        manager: '张三',
        status: 'normal',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        boundaryCode: 'BD002',
        boundaryName: '副坝西段边界',
        boundaryType: 'sub-dam',
        coordinates: '116.345678,39.876543;116.456789,39.987654',
        length: 800,
        area: 9800,
        manager: '李四',
        status: 'maintenance',
        createTime: '2024-01-16 14:20:00'
      },
      {
        id: 3,
        boundaryCode: 'BD003',
        boundaryName: '溢洪道边界',
        boundaryType: 'spillway',
        coordinates: '116.567890,39.098765;116.678901,39.109876',
        length: 450,
        area: 5200,
        manager: '王五',
        status: 'normal',
        createTime: '2024-01-17 09:15:00'
      },
      {
        id: 4,
        boundaryCode: 'BD004',
        boundaryName: '输水隧洞边界',
        boundaryType: 'tunnel',
        coordinates: '116.789012,39.210987;116.890123,39.321098',
        length: 320,
        area: 2800,
        manager: '赵六',
        status: 'abnormal',
        createTime: '2024-01-18 16:45:00'
      },
      {
        id: 5,
        boundaryCode: 'BD005',
        boundaryName: '库区北部边界',
        boundaryType: 'reservoir-area',
        coordinates: '116.901234,39.432109;116.012345,39.543210',
        length: 2100,
        area: 45600,
        manager: '孙七',
        status: 'normal',
        createTime: '2024-01-19 11:30:00'
      }
    ]
    let list = [...mockData]
    if (list.length < 10) {
      const target = Math.floor(Math.random() * 41) + 10
      const templates = mockData
      const types = ['main-dam', 'sub-dam', 'spillway', 'tunnel', 'reservoir-area']
      const statuses = ['normal', 'maintenance', 'abnormal']
      while (list.length < target) {
        const base: any = templates[list.length % templates.length]
        const idx = list.length + 1
        list.push({
          ...base,
          id: idx,
          boundaryCode: `BD${String(idx).padStart(3, '0')}`,
          boundaryName: `${base.boundaryName}-${idx}`,
          boundaryType: types[idx % types.length],
          status: statuses[idx % statuses.length],
          manager: base.manager
        })
      }
    }
    tableData.value = list
    pagination.total = list.length
  } catch (error) {
    ElMessage.error('获取边界列表失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除边界
const deleteBoundary = async (ids: number[]) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('删除成功')
    fetchBoundaryList()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 导出数据
const exportBoundaryData = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  fetchBoundaryList()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    boundaryName: '',
    boundaryType: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentFormData.value = null
  isView.value = false
  formDialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentFormData.value = { ...row }
  isView.value = true
  formDialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentFormData.value = { ...row }
  isView.value = false
  formDialogVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除边界"${row.boundaryName}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteBoundary([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 条边界记录吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteBoundary(selectedIds.value)
  })
}

// 导出
const handleExport = () => {
  exportBoundaryData()
}

// 查看地图
const handleViewMap = () => {
  mapDialogVisible.value = true
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchBoundaryList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchBoundaryList()
}

// 表单成功回调
const handleFormSuccess = () => {
  fetchBoundaryList()
}

// 初始化
onMounted(() => {
  fetchBoundaryList()
})
</script>

<style scoped>
.reservoir-boundary-container {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>